<template>
    <div class="task-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="任务名称:">
                                <el-input
                                    v-model="searchForm.taskName"
                                    placeholder="输入任务名称"
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="任务类型:">
                                <el-select v-model="searchForm.taskType" placeholder="请选择" style="width: 120px">
                                    <el-option label="全部" value="" />
                                    <el-option label="浏览文章" value="1" />
                                    <el-option label="观看视频" value="2" />
                                    <el-option label="购买商品" value="3" />
                                    <el-option label="购买服务" value="4" />
                                    <el-option label="邀请" value="5" />
                                    <el-option label="签到" value="6" />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增按钮 -->
        <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAddTask">新增任务</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
                    <el-table-column type="index" label="序" width="60" align="center" />
                    <el-table-column prop="taskName" label="任务名称" />
                    <el-table-column prop="taskType" label="任务类型" align="center">
                        <template #default="{ row }">
                            {{ getTaskTypeName(row.taskType) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="rewardType" label="奖励类型" align="center">
                        <template #default="{ row }">
                            {{ getRewardTypeName(row.rewardType) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="completionQuantity" label="完成数量" align="center" />
                    <el-table-column prop="taskCycle" label="任务周期" align="center">
                        <template #default="{ row }">
                            {{ getTaskCycleName(row.taskCycle) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="startTime" label="开始时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.startTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        总共{{ pagination.total }}条记录,当前在第{{ pagination.currentPage }}页
                    </div>
                    <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handlePageChange" />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { CirclePlusFilled } from '@element-plus/icons-vue'
import { Task, TaskQueryParams } from '@/types/task'
import { getTaskPage, deleteTask } from '@/api/system/task'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
    taskName: '',
    taskType: '',
    language: '',
    memberLevel: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref<Task[]>([])

// 分页数据
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 获取任务列表数据
const getData = async () => {
    loading.value = true
    try {
        const params: TaskQueryParams = {
            current: pagination.currentPage,
            size: pagination.pageSize,
            ...(searchForm.taskName && { taskName: searchForm.taskName }),
            ...(searchForm.taskType && { taskType: parseInt(searchForm.taskType) }),
            ...(searchForm.language && { language: searchForm.language }),
            ...(searchForm.memberLevel && { memberLevel: searchForm.memberLevel })
        }
        
        console.log('请求参数:', params)
        const res = await getTaskPage(params)
        console.log('API响应:', res)
        
        const responseData = res as any
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || []
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取任务数据失败'
            ElMessage.error(errorMsg)
            tableData.value = []
            pagination.total = 0
        }
    } catch (error) {
        console.error('获取任务数据失败:', error)
        ElMessage.error('网络错误，请稍后重试')
        tableData.value = []
        pagination.total = 0
    } finally {
        loading.value = false
    }
}

// 搜索处理
const handleSearch = () => {
    pagination.currentPage = 1
    getData()
}

// 重置搜索
const handleReset = () => {
    searchForm.taskName = ''
    searchForm.taskType = ''
    searchForm.language = ''
    searchForm.memberLevel = ''
    pagination.currentPage = 1
    getData()
}

// 新增任务
const handleAddTask = () => {
    router.push('/task-form')
}

// 时间格式化函数
const formatTime = (timeStr: string | null) => {
    if (!timeStr) return '-'
    try {
        const date = new Date(timeStr)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
    } catch (error) {
        return timeStr
    }
}

// 获取任务类型名称
const getTaskTypeName = (taskType: number) => {
    const typeMap: { [key: number]: string } = {
        1: '浏览文章',
        2: '观看视频',
        3: '购买商品',
        4: '购买服务',
        5: '邀请',
        6: '签到'
    }
    return typeMap[taskType] || '未知'
}

// 获取奖励类型名称
const getRewardTypeName = (rewardType: number) => {
    const rewardTypeMap: { [key: number]: string } = {
        1: '积分',
        2: '道具',
        3: '积分+道具'
    }
    return rewardTypeMap[rewardType] || '未知'
}

// 获取任务周期名称
const getTaskCycleName = (cycle: number) => {
    const cycleMap: { [key: number]: string } = {
        1: '按日',
        2: '按周',
        3: '活动'
    }
    return cycleMap[cycle] || '未知'
}

// 查看任务
const handleView = (row: Task) => {
    ElMessage.info(`查看任务: ${row.taskName}`)
}

// 编辑任务
const handleEdit = (row: Task) => {
    router.push(`/task-form/${row.id}`)
}

// 删除任务
const handleDelete = async (row: Task) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除任务"${row.taskName}"吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        
        loading.value = true
        const res = await deleteTask(row.id)
        const responseData = res as any
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功')
            getData() // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败'
            ElMessage.error(errorMsg)
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除任务失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    } finally {
        loading.value = false
    }
}

// 分页处理
const handlePageChange = (page: number) => {
    pagination.currentPage = page
    getData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    getData()
}

onMounted(() => {
    // 页面加载完成，加载初始数据
    getData()
})
</script>

<style scoped>
.task-list-container {
    padding: 20px;
}

/* 搜索区域样式 */
.search-section {
    margin-bottom: 20px;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-left {
    flex: 1;
}

.search-right {
    display: flex;
    gap: 12px;
    margin-left: 20px;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
}

.pagination-info {
    font-size: 14px;
    color: #606266;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
    padding: 20px;
}

:deep(.el-table) {
    border-radius: 4px;
}

:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-form-item) {
    margin-bottom: 16px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    border-radius: 4px;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 4px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
    border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .task-list-container {
        padding: 10px;
    }

    .search-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
        padding: 15px;
    }

    .search-right {
        margin-left: 0;
        width: 100%;
        justify-content: flex-start;
    }

    .search-form .el-form-item {
        margin-bottom: 15px;
    }
}
</style>
